var WxParse = require('../../wxParse/wxParse.js');
var util = require('../../utils/util.js')
import Toast from '../../dist/toast/toast';
var md5 = require('../../utils/md5.js')
var app = getApp();
Page({
    /**
     * 页面的初始数据  showPopup:授权状态,默认是false
     */
    data: {
        postData: {},
        navigateTitle: "",
        id: "",
        collectUrl: '/images/icon/collect.png',
        placeholder: "白活点啥呗...",
        isCollect: '1',
        isShow: false,
        menuBackgroup: false,
        showPopup: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        loginSuccess: false,
        username: '',
        password: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        wx.showLoading({
            title: '拼命加载中'
        });
        if (options.share) {
            console.log("分享页面过来的")
            //分享页面过来的需要把原来分享者已经喜欢状态的颜色给去掉，改为非喜欢状态，因为新人进来肯定非喜欢
            app.globalData.userInfo = null
            this.setData({
                share: options.share,
                isCollect: '1',
            });
            var id = options.id;
            var title = options.title;
            this.data.navigateTitle = title;
            this.data.id = id;
            this.getData(id)
        }else{
            var id = options.id;
            var title = options.title;
            this.data.navigateTitle = title;
            this.data.id = id;
            this.getData(id)
            console.log("正常页面过来的")
        }
    },

    /**
     * 获取博客详情
     */
    getData(id){
        let that = this;
        var timestamp = Date.parse(new Date())
        wx.request({
            url: app.globalData.apiBase +
                "/blog/getBlogDetails?id=" + id,
            method:'get',
            header: {
                'content-type': 'application/json',
                'clientType': 'WX',
                'Authorization': 'Bearer ' + wx.getStorageSync("token"),
                'timestamp': timestamp,
                'sign': md5.hexMD5('timestamp=' + timestamp + wx.getStorageSync("token")),
                'signType': 'MD5'
            },
            success(res) {
                if(res.data.respCode==='0000'){
                    let dataResult=res.data.respResult
                    //小程序富文本内容转换
                    WxParse.wxParse('article', 'html', dataResult.content, that);
                    dataResult.createTime = util.date_time(dataResult.createTime);
                    that.setData({
                        postData: dataResult,
                        isCollect: dataResult.isCollect
                    });
                    wx.hideLoading();
                }else if(res.data.respCode==='3000'){
                    wx.showToast({
                        title: res.data.respMessage,
                        icon: 'none',
                        duration: 2000
                    })
                }
            },
            fail() {

            }
        })
    },

    /**
     * 授权登录(为了当用户从分享页进来，没有授权信息，导致后台接口调用发生权限不足的情况)
     */
    checkLogin() {
        var p = new Promise(function (resolve, reject) {
                wx.getSetting({    //获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限 返回值：请求过的权限可以通过res.authSetting拿到
                    success: (res) => {
                        if (res.authSetting['scope.userInfo']) { //用户是否授权通过(弹出框用户点击了确定)res.authSetting[scope.userInfo]可以判断
                            wx.getUserInfo({
                                success: (res) => {
                                    app.globalData.userInfo = res.userInfo;
                                    resolve(res);
                                },
                                fail: (error) => {
                                    console.log('系统错误')
                                }
                            })
                        }
                    },
                    fail: (error) => {
                        console.log('获取用户信息失败');
                        reject(error)
                    }
                })
        })
        return p
    },
    direct() {
        let url = "/pages/launch/launch";
        wx.switchTab({
            url: url
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        wx.setNavigationBarTitle({
            title: this.data.navigateTitle
        })
    },
    /**
     * 返回首页
     */
    navigateBack() {
        getCurrentPages().pop()
        wx.redirectTo({
            url: '../posts/post'
        })
    },
    addCollect(){
        this.doNext()
    },
    /**
     * 收藏文章
     */
    doNext() {
        // 1.查看授权状态
        if (app.globalData.userInfo != null) { //如果是分享过来的页面，用户手机里面的userinfo肯定为空
            this.setData({
                showPopup: false
            })
        }else{
            this.setData({
                showPopup: true
            })
        }
        console.log(this.data.showPopup + "--------授权状态")
        if (this.data.showPopup) {
            console.log("开始调用登录")
            this.checkLogin()
                .then(this.trueLogin)
                .then(this.collectSubmit)
        }else{
            this.collectSubmit()
        }
    },
    //收藏提交
    collectSubmit(){
        this.setData({
            showPopup:false
        })
        let isCollection= this.data.isCollect=="0"?"1":"0";
        var dataUrl = app.globalData.apiBase +
            "/blog/addCollect?articleId=" + this.data.id+"&flag="+isCollection;
        util.ajax(dataUrl, "get", null,(dataRespResult)=>{
            this.setData({
                isCollect:isCollection
            });
            Toast(dataRespResult);
        })
    },
    /**
     * 真正调用后台登录接口
     * @returns {Promise<any>}
     */
    trueLogin() {
        var p = new Promise(function (resolve, reject) {
            let that = this;
            //调用接口获取登录凭证（code）
            wx.login({
                success: (res) => {
                    wx.request({
                        url: app.globalData.apiBase + '/blog/loginSubmit',
                        data: {
                            code: res.code,
                            nickname: app.globalData.userInfo.nickName,
                            avatar: app.globalData.userInfo.avatarUrl
                        },
                        method: 'POST',
                        header: {
                            'content-type': 'application/json',
                            'clientType': 'WX',
                            'appId': 'wx56561420351f2442'
                        },
                        success: (res) => {
                            if (res.data.respCode === '0000') {
                                app.globalData.userId = res.data.respResult.userId;
                                app.globalData.token = res.data.respResult.token;
                                resolve(res)
                            } else {
                                wx.showToast({
                                    title: '',
                                    icon: 'none',
                                    duration: 1500
                                })
                            }
                        },
                        fail: (error) => {
                            reject(error)
                        }
                    })
                },
                fail: (error) => {
                    console.log('获取用户信息失败');
                    reject(error)
                }
            })
        })
        return p
    },
    // 调用微信登录接口
    login() {
        var p = new Promise((resolve, reject) => {
            let that = this;
            //调用接口获取登录凭证（code）
            wx.login({
                success: (res) => {
                    wx.request({
                        url: app.globalData.apiBase + '/blog/loginSubmit',
                        data: {
                            code: app.globalData.userInfo.code,
                            nickname: app.globalData.userInfo.nickName,
                            avatar: app.globalData.userInfo.avatarUrl
                        },
                        method: 'POST',
                        header: {
                            'content-type': 'application/json',
                            'clientType': 'WX',
                            'appId': 'wx56561420351f2442'
                        },
                        success(res) {
                            if (res.data.respCode === '0000') {
                                app.globalData.userId = res.data.respResult.userId;
                                app.globalData.token = res.data.respResult.token;

                            } else {
                                wx.showToast({
                                    title: '',
                                    icon: 'none',
                                    duration: 1500
                                })
                            }
                        },
                        fail() {

                        }
                    })
                    resolve(res)
                }
            })
        })
        return p
    },

    /**
     * 是否显示功能菜单
     */
    showHideMenu: function () {
        this.setData({
            isShow: !this.data.isShow,
            isLoad: false,
            menuBackgroup: !this.data.false
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
            title: this.data.postData.title,
            path: '/pages/post-detail/post-detail?id=' + this.data.id + "&title=" + '德丽小博' + "&share=1"
        }
    },
    /**
     * 回到首页(分享的时候)
     */
    onBackHome: function () {
        wx.reLaunch({
            url: '/pages/launch/launch?share=1"'
        })
    }

})
